#!/usr/bin/env python3
"""
Build script for libqtile's CFFI helpers.
"""

from __future__ import annotations

import sys
from subprocess import run
from typing import NamedTuple


class Builder(NamedTuple):
    """
    A build script. If 'features' is None, this script is required.
    """

    name: str
    path: str
    features: str | None


scripts = [
    Builder("PulseAudio interface", "./libqtile/widget/pulseaudio_ffi.py", "PulseVolume widget"),
    Builder(
        "Wayland libinput interface",
        "./libqtile/backend/wayland/libinput_ffi_build.py",
        "Wayland backend input configurability",
    ),
]


def build(builder: Builder, verbose: bool) -> bool:
    print("Building", builder.name)

    p = run(["python3", builder.path], capture_output=True)

    if p.returncode:
        print("    Failed!")
        if builder.features:
            print("    This is optional and is needed for:", builder.features)
        else:
            print("    This component is required.")

        if verbose:
            print(p.stderr.decode())

        return True

    return False


if __name__ == "__main__":
    verbose = "-v" in sys.argv
    errors = False

    for builder in scripts:
        errors |= build(builder, verbose)

    if errors and not verbose:
        print("\nFailures for optional components can be ignored.")
        print("Pass -v to print full stack traces.")
